package com.neusoft.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import java.util.Iterator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.mapper.CartMapper;
import com.neusoft.mapper.OrderDetailetMapper;
import com.neusoft.mapper.OrdersMapper;
import com.neusoft.po.Cart;
import com.neusoft.po.OrderDetailet;
import com.neusoft.po.Orders;
import com.neusoft.service.OrdersService;
import com.neusoft.util.CommonUtil;

@Service
public class OrdersServiceImpl implements OrdersService {

	@Autowired
	private CartMapper cartMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private OrderDetailetMapper orderDetailetMapper;

	@Override
	@Transactional
	public int createOrders(Orders orders) {
		// 验证订单数据
		if (orders == null || orders.getUserId() == null || orders.getBusinessId() == null) {
			throw new IllegalArgumentException("Invalid order data");
		}

		// 判断是否为虚拟订单
		boolean isVirtualOrder = orders.getBusinessId() == 11001; // 假设虚拟商家ID为1001

		if (!isVirtualOrder) {
			// 1、查询当前用户购物车中当前商家的所有食品
			Cart cart = new Cart();
			cart.setUserId(orders.getUserId());
			cart.setBusinessId(orders.getBusinessId());
			List<Cart> cartList = cartMapper.listCart(cart);

			// 验证购物车是否为空
			if (cartList == null || cartList.isEmpty()) {
				throw new IllegalStateException("Shopping cart is empty");
			}

			// 2、创建订单（返回生成的订单编号）
			orders.setOrderDate(CommonUtil.getCurrentDate());
			ordersMapper.saveOrders(orders);
			int orderId = orders.getOrderId();

			// 3、批量添加订单明细
			List<OrderDetailet> list = new ArrayList<>();
			for (Cart c : cartList) {
				OrderDetailet od = new OrderDetailet();
				od.setOrderId(orderId);
				od.setFoodId(c.getFoodId());
				od.setQuantity(c.getQuantity());
				list.add(od);
			}
			orderDetailetMapper.saveOrderDetailetBatch(list);

			// 4、从购物车表中删除相关食品信息
			cartMapper.removeCart(cart);
		} else {
			// 处理虚拟订单
			orders.setOrderDate(CommonUtil.getCurrentDate());
			ordersMapper.saveOrders(orders);
			int orderId = orders.getOrderId();

			// 创建虚拟订单明细
			OrderDetailet orderDetailet = new OrderDetailet();
			orderDetailet.setOrderId(orderId);
			orderDetailet.setFoodId(1001); // 虚拟食品ID
			orderDetailet.setQuantity((int) Math.round(orders.getOrderTotal()));

			// 使用批量插入方法保存虚拟订单明细
			List<OrderDetailet> list = new ArrayList<>();
			list.add(orderDetailet);
			orderDetailetMapper.saveOrderDetailetBatch(list);
		}

		return orders.getOrderId();
	}

	@Override
	public List<Orders> listOrdersByUserId(String userId) {
		List<Orders> orderList = ordersMapper.listOrdersByUserId(userId);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date currentDate = new Date();
        List<Orders> ordersToRemove = new ArrayList<>();
		Iterator<Orders> iterator =  orderList.iterator();
		while (iterator.hasNext()) {
			Orders order = iterator.next();
			String orderDateStr = order.getOrderDate();
			try {
				Date orderDate = formatter.parse(orderDateStr);
				long timeDifferenceMillis = currentDate.getTime() - orderDate.getTime();
				//long timeDifferenceHours = timeDifferenceMillis / (60 * 60 * 1000);
				long diffMinutes = timeDifferenceMillis / (1000*60);
				if (order.getOrderState() == 0 && diffMinutes > 15) {
					// 从数据库中删除订单
					int a = order.getOrderId();
					ordersMapper.removeOrder(a);
					// 从订单列表中删除订单
					ordersToRemove.add(order);
				}
			} catch (ParseException e) {
				// 处理时间解析异常
				e.printStackTrace();
				// 可以记录日志或者其他处理方式
			}
		}
		orderList.removeAll(ordersToRemove);
		return orderList;
	}

	@Override
	public Orders getOrdersById(Integer orderId) {
		return ordersMapper.getOrdersById(orderId);
	}


	@Override
	public void updateOrderStateById(Integer orderId) {
		ordersMapper.updateOrderStateById(orderId);
	}

	@Override
	@Transactional
	public int payOrdersById(Integer orderId) {
		// 假设1表示已支付
		int orderStatus = 1;
		return ordersMapper.updateOrder(orderId, orderStatus);
	}
	@Override
	public void saveComment(Integer orderId,String comment) {
		ordersMapper.saveComment(orderId,comment);
	}

	@Override
	public List<String> getcomment(Integer businessId) {
		return ordersMapper.getcomment(businessId);
	}

}
